//
// Created by chen on 25-5-2.
//

#include "INA199Sensor.h"

#include <cstdio>

// 采样电阻值（单位：欧姆）
constexpr float SHUNT_RESISTANCE = 0.02f;
// INA199增益（V/V）
constexpr float INA199_GAIN = 50.0f;
// 基准电压（V）
constexpr float VREF = 1.65f;
// ADC参考电压（V）
constexpr float ADC_REF_VOLTAGE = 3.3f;
// ADC分辨率
constexpr uint32_t ADC_RESOLUTION = 4096; // 12位ADC


INA199Sensor::INA199Sensor(ADC_HandleTypeDef* adcHandle, uint32_t channel)
    : hadc(adcHandle), adcChannel(channel) {
    // 配置ADC通道
    ADC_ChannelConfTypeDef sConfig = {0};
    sConfig.Channel = adcChannel;
    sConfig.Rank = 1;
    sConfig.SamplingTime = ADC_SAMPLETIME_28CYCLES_5;
    HAL_ADC_ConfigChannel(hadc, &sConfig);
}

uint16_t INA199Sensor::readAdcRaw() {
    HAL_ADC_Start(hadc);
    HAL_ADC_PollForConversion(hadc, 10);
    return HAL_ADC_GetValue(hadc);
}

float INA199Sensor::readOutputVoltage() {
    uint16_t adcValue = readAdcRaw();
    return (float)adcValue * ADC_REF_VOLTAGE / ADC_RESOLUTION;
}

float INA199Sensor::readCurrent() {
    float outputVoltage = readOutputVoltage();
    // 计算公式：I = (Vout - Vref) / (Gain * Rshunt)
    return (outputVoltage - VREF) / (INA199_GAIN * SHUNT_RESISTANCE);
}

float INA199Sensor::readPower(float busVoltage) {
    float current = readCurrent();
    return current * busVoltage;
}

/**
 * 兼容c 函数
 * @param hadc
 */

uint16_t adc_ch1_val = 0;
uint16_t adc_ch2_val = 0;
uint8_t adc_conv_index = 0;
#include "usart.h"
extern "C"  void INA199Sensor::AdcCallback(ADC_HandleTypeDef *hadc) {
    //是adc1 的 中断
    if (hadc==&hadc1) {
        uint16_t value = HAL_ADC_GetValue(hadc);

        if (adc_conv_index == 0)
        {
            adc_ch1_val = value;
            adc_conv_index = 1;
        }
        else if (adc_conv_index == 1)
        {
            adc_ch2_val = value;
            adc_conv_index = 0;
        }
        printf("adc_ch2_val:%d\n", adc_ch2_val);
        // 继续开启下一次转换
        HAL_ADC_Start_IT(hadc);

    }
}


extern "C" void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc) {
    if (hadc->Instance == ADC1) {
        // 调用C++静态回调
        INA199Sensor::AdcCallback(hadc);
    }
}